package com.autguigu.crowd.util;

import com.autguigu.crowd.constant.CrowdConstant;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 尚筹网项目通用工具类
 *
 * @author wmb
 *
 * @since 2021-1-18
 */
public class CrowdUtil {

    private static Logger logger = LoggerFactory.getLogger(CrowdUtil.class);

    /**
     * 对明文字符串进行md5加密
     *
     * @param source    传入的明文字符串
     *
     * @return
     */
    public static String md5(String source) {
        // 1.判断source是否有效
        if (StringUtils.isBlank(source)) {
            // 2.如果不是有效的字符串抛出异常
            throw new RuntimeException(CrowdConstant.MESSAGE_LOGIN_STRING_INVALID);
        }

        try {
            // 3.获取MessageDigest对象
            String algorithm = "md5";
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            // 4.获取明文字符串对应的字节数组
            byte[] input = source.getBytes();
            // 5.执行加密
            byte[] output = messageDigest.digest(input);
            // 6.创建BigInteger对象
            int signum = 1;
            BigInteger bigInteger = new BigInteger(signum, output);
            // 7.按照16进制将BigInteger的值转换为字符串
            int radix = 16;
            return bigInteger.toString(radix).toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            logger.error(e.getMessage());
        }

        return null;
    }

    /**
     * 判断当前请求是否是ajax请求
     *
     * @param request   请求对象
     *
     * @return
     *          true：当前请求是Ajax请求
     *          false：当前请求不是Ajax请求
     */
    public static boolean judgeRequestType(HttpServletRequest request) {
        // 1.获取请求消息头
        String acceptHeader = request.getHeader("Accept");
        String xRequestHeader = request.getHeader("X-Requested-With");

        // 2.判断
        return (StringUtils.isNoneBlank(acceptHeader) && acceptHeader.contains("application/json")) ||
                (StringUtils.isNoneBlank(xRequestHeader) && xRequestHeader.contains("XMLHttpRequest"));
    }
}
